from Queue import Queue
from mbserver.server.core.worker import WorkerThread
from mbserver.server.core.worker import ParserThread
from mbserver.server import settings

import logging
log = logging.getLogger('metabus')

class Singleton(object):
   def __new__(cls, *args, **kwargs):
       if '_inst' not in vars(cls):
           cls._inst = object.__new__(cls, *args, **kwargs)
       return cls._inst

class MBThreadPool(Singleton):
    """
        This class must be Singleton, becouse it's suppose to exist only one
        of this pool per process. The total number of threads will be 
        number of process x number of MBThreadPool threads.
    """
    __pool = None

    def __init__ (self):
        if MBThreadPool.__pool is None:
            self.ioworkers = []
            self.parser = None
            self.requests = Queue(0)
            self.bg_requests = Queue(0)
            self.responses = Queue(0)
    
            for proc in range(settings.THREADS_NUMBER):
                w = WorkerThread(self.requests, self.bg_requests, self.responses)
                w.start()
                self.ioworkers.append(w)
        
            self.parser = ParserThread(self.responses)
            self.parser.start()

        MBThreadPool.__pool = self

    def __del__(self):
        for i in range(len(self.ioworkers)):
            self.ioworkers.pop().dismiss()
        
        self.parser.dismiss()
